package cardwall.client.model;

import cardwall.shared.CardWallService;
import cardwall.shared.CardWallServiceAsync;
import cardwall.shared.Task;
import cardwall.client.ApplicationFacade;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.Window;
import com.google.gwt.core.client.GWT;

import java.util.List;

/**
 * @author $LastChangedBy: vogensen $
 * @version $Revision: 2 $
 */
public class TasksProxy extends Proxy {
    public static final String PROXYNAME = "TasksProxy";

    private CardWallServiceAsync cardWallService;

    public TasksProxy() {
        super(PROXYNAME);
        init();
    }

    public void init() {
        cardWallService = (CardWallServiceAsync) GWT.create(CardWallService.class);
        ServiceDefTarget endpoint = (ServiceDefTarget) cardWallService;
        String moduleRelativeURL = GWT.getModuleBaseURL() + "cardwall";
        endpoint.setServiceEntryPoint(moduleRelativeURL);
    }

    public void refreshTasks() {
        cardWallService.getTaskList(new AsyncCallback<List<Task>>() {
            public void onFailure(Throwable caught) {
                //TODO send notification
                Window.alert("RPC to getTask() failed.");
            }

            public void onSuccess(List<Task> result) {
                setData(result);
                sendNotification(ApplicationFacade.TASKS_CHANGED, result, ApplicationFacade.NOTIFICATIONTYPE_DEFAULT);
            }
        });
    }

    public void createTask() {
        cardWallService.createTask(new AsyncCallback<Task>() {
            public void onFailure(Throwable caught) {
                Window.alert("RPC to createTask() failed.");
            }

            public void onSuccess(Task task) {
                getTaskList().add(task);
                sendNotification(ApplicationFacade.TASKS_CHANGED, getData(), ApplicationFacade.NOTIFICATIONTYPE_DEFAULT);
            }
        });
    }

    private List<Task> getTaskList() {
        return (List<Task>)getData();
    }

    public void updateTask(Task task) {
        getTaskList().remove(task);
        cardWallService.updateTask(task, new AsyncCallback<Task>() {
            public void onFailure(Throwable caught) {
                Window.alert("RPC to updateTask() failed.");
            }

            public void onSuccess(Task task) {
                getTaskList().add(task);
                sendNotification(ApplicationFacade.TASKS_CHANGED, getData(), ApplicationFacade.NOTIFICATIONTYPE_DEFAULT);
            }
        });
    }
}
